package com.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.bean.Users;
import com.dao.UsersDAO;
import com.util.Page;

/**
 * A data access object (DAO) providing persistence and search support for Users
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see com.Users
 * @author MyEclipse Persistence Tools
 */

public class UsersDAOImpl extends HibernateDaoSupport implements UsersDAO {
	private static final Logger log = Logger.getLogger(UsersDAOImpl.class);
	// property constants
	public static final String USERNAME = "username";
	public static final String PASSWORD = "password";

	// 分页设置
	public List findByPage(final String hql, final Page page) {
		log.info("findByPage Users");
		try {
			return getHibernateTemplate().executeFind(new HibernateCallback() {
				public Object doInHibernate(Session session) {
					return session
							.createQuery(hql)
							.setFirstResult(
									(page.getCurrentPage() - 1)
											* page.getPageSize())
							.setMaxResults(page.getPageSize()).list();
				}
			});
		} catch (RuntimeException re) {
			log.error("findByPage failed", re);
			throw re;
		}
	}

	public void save(Users transientInstance) {
		log.info("saving Users instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.info("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void saveBatch(List entities)throws Exception{
		log.info("batch saving Users instance");
		try {
			getHibernateTemplate().saveOrUpdateAll(entities);
			log.info("batch saving successful");
		} catch (RuntimeException re) {
			log.error("batch saving failed", re);
			throw re;
		}
	}

	public void delete(Users persistentInstance) {
		log.info("deleting Users instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.info("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public void deleteBatch(List entities) {
		log.info("batch deleting Users instance");
		try {
			getHibernateTemplate().deleteAll(entities);
			log.info("batch delete successful");
		} catch (RuntimeException re) {
			log.error("batch delete failed", re);
			throw re;
		}
	}

	public Users findById(java.lang.Integer id) {
		log.info("getting Users instance with id: " + id);
		try {
			Users instance = (Users) getHibernateTemplate().get(
					"com.bean.Users", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(Users instance) {
		log.info("finding Users instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.info("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.info("finding Users instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Users as model where model."
					+ propertyName + "like ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByUsername(Object username) {
		return findByProperty(USERNAME, username);
	}

	public List findByPassword(Object password) {
		return findByProperty(PASSWORD, password);
	}

	public List<Users> findAll(Page page) {
		log.info("finding all Users instances");
		try {
			String queryString = "from Users";
			int totalSize = getHibernateTemplate().find(queryString).size();// 得到记录条数
			page.setTotalSize(totalSize);
			return findByPage(queryString.toString(),page);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Users merge(Users detachedInstance) {
		log.info("merging Users instance");
		try {
			Users result = (Users) getHibernateTemplate().merge(
					detachedInstance);
			log.info("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Users instance) {
		log.info("attaching dirty Users instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.info("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Users instance) {
		log.info("attaching clean Users instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.info("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static UsersDAOImpl getFromApplicationContext(ApplicationContext ctx) {
		return (UsersDAOImpl) ctx.getBean("UsersDAOImpl");
	}

	@Override
	public List findUser(String username, String password) {
		log.info("findUser String username password");
		try {
			String queryString = "from Users where username = ? and password = ?";
			return getHibernateTemplate().find(queryString,
					new Object[] { username, password });
		} catch (RuntimeException re) {
			log.error("find user failed", re);
			throw re;
		}
	}

	@Override
	public List findByQuery(Users user, Page page) {
		// TODO Auto-generated method stub
		log.info("findByQuery Users instance");
		StringBuilder str = new StringBuilder();
		String queryString = "from Users ";
		try {
			str.append(queryString);
			if (user != null) {
				if (user.getUsername() != null
						&& !user.getUsername().equals("")) {
					str.append("where username like '" + user.getUsername()
							+ "'");
				} else if (user.getPassword() != null
						&& !user.getPassword().equals("")) {
					str.append(" and password like '" + user.getPassword()
							+ "'");
				}
			}
			log.info(str.toString());
			// return getHibernateTemplate().find(str.toString());
			int totalSize = getHibernateTemplate().find(str.toString()).size();// 得到记录条数
			page.setTotalSize(totalSize);
			return findByPage(str.toString(),page);
		} catch (RuntimeException re) {
			log.error("find user failed", re);
			throw re;
		}
	}
}